package com.birdy.service.impl;

import com.birdy.code.CheckComment;
import com.birdy.mapper.CheckMapper;
import com.birdy.service.ICheckService;
import com.birdy.vo.Check;
import com.birdy.vo.CheckDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author birdy
 * @date 2022/5/4 8:50 AM
 */
@Service
@Slf4j
public class CheckServiceImpl implements ICheckService {
    @Autowired
    private CheckMapper checkMapper;

    @Transactional
    @Override
    public int addCheck(Check check) {
        // 解析check评级
        int comment = parseCheck(check);
        log.info("解析评分成功");
        // 新增check到数据库
        final int checkId = checkMapper.check(CheckDTO.builder().openid(check.getOpenid()).comment(comment).build());
        log.info("打卡成功");
        final String openid = check.getOpenid();
        // 把所有任务放到achieve中
        check.getGoals().forEach(goalSummary ->
                checkMapper.achieve(goalSummary.getGoal().getId(), openid, checkId));
        log.info("任务逐一打卡成功");
        return comment;
    }

    @Override
    public Timestamp getLatestDay(String openid) {
        return checkMapper.getLatestDay(openid);
    }

    public int parseCheck(Check check){
        int total = check.getGoals().size();
        AtomicInteger finished = new AtomicInteger();
        check.getGoals().forEach(goal -> {
            if (goal.getFinished() == 1) {
                finished.getAndIncrement();
            }
        });
        int comment = finished.get() * 100 / total;
        log.info("total:{}, finished:{}, comment:{}", total, finished, comment);
        return CheckComment.getCommentByScore(comment);
    }
}
